package com.example.zzx.dovebook.user;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;

import com.example.baselibrary.constant.Constant;
import com.example.zzx.dovebook.user.model.User;

/**
 * 管理用户数据
 * @author imurluck
 * @time 18-9-22 下午3:46
 */

public class UserManager {

    private static final String TAG = "UserManager";

    private User mLoginUser;

    private double longitude;
    private double latitude;

    private static final Uri sUserUri = Uri.parse("content://" + Constant.PROVIDER_AUTHORItIES + "/user");

    private static volatile UserManager sInstance;

    private Context mContext;

    private UserManager(Context context) {
        mContext = context.getApplicationContext();
    }

    public static UserManager getInstance(Context context) {
        if (sInstance == null) {
            synchronized (UserManager.class) {
                sInstance = new UserManager(context);
            }
        }
        return sInstance;
    }

    private ContentValues setupUserContentValue(User user, boolean setupLoginTime) {
        ContentValues values = new ContentValues();
        values.put("user_id", user.getUserId());
        values.put("user_name", user.getUserName());
        values.put("user_password", user.getUserPassword());
        values.put("user_phone", user.getUserPhone());
        values.put("user_sex", user.getUserSex());
        values.put("user_avatar_path", user.getUserAvatarPath());
        values.put("user_latitude", user.getUserLatitude());
        values.put("user_longitude", user.getUserLongitude());
        values.put("create_at", user.getCreateAt());
        values.put("update_at", user.getUpdateAt());
        if (setupLoginTime) {
            values.put("login_at", System.currentTimeMillis());
            values.put("is_login", 1);
        }
        return values;
    }

    public String getLoginUserId() {
        User loginUser = getLoginUser();
        if (loginUser != null) {
            return loginUser.getUserId();
        }
        return null;
    }

    public String getLoginUserName() {
        User loginUser = getLoginUser();
        if (loginUser != null) {
            return loginUser.getUserName();
        }
        return null;
    }

    public User getLoginUser() {
        if (mLoginUser == null) {
            mLoginUser = queryLoginUser();
        }
        return mLoginUser;
    }

    private User queryLoginUser() {
        ContentResolver resolver = mContext.getContentResolver();
        Cursor cursor = resolver.query(sUserUri, null, "is_login = ?", new String[] {"1"}, null);
        if (cursor == null || cursor.moveToFirst() == false) {
            return null;
        }
        User user = mapUser(cursor);
        mLoginUser = user;
        cursor.close();
        return user;
    }

    private User mapUser(Cursor cursor) {
        User user = new User();
        user.setUserId(cursor.getString(0));
        user.setUserName(cursor.getString(1));
        user.setUserPassword(cursor.getString(2));
        user.setUserPhone(cursor.getLong(3));
        user.setUserSex(cursor.getString(4));
        user.setUserAvatarPath(cursor.getString(5));
        user.setUserLatitude(cursor.getString(6));
        user.setUserLongitude(cursor.getString(7));
        user.setCreateAt(cursor.getLong(8));
        user.setUpdateAt(cursor.getLong(9));
        user.setLogin(cursor.getInt(11) == 1 ? true : false);
        return user;
    }

    /**
     * 判断登录状态,登录保质期为30天
     * @param loginTime 上次登录时间
     * @return
     */
    private boolean isLoginOverdu(long loginTime) {
        long currentTime = System.currentTimeMillis();
        return currentTime >= loginTime + 1000L * 60L * 60L * 24L * 30L;
    }


    public User queryUserById(String userId) {
        ContentResolver resolver = mContext.getContentResolver();
        Cursor cursor = resolver.query(sUserUri, null, "user_id = ?", new String[] {userId}, null);
        if (cursor == null || cursor.moveToFirst() == false) {
            return null;
        }
        User user = mapUser(cursor);
        cursor.close();
        return user;
    }

    public void login(User user) {
        if (queryUserById(user.getUserId()) == null) {
            insertUser(user);
        } else {
            updateUser(user, true);
        }
    }

    public void signUp(User user) {
        insertUser(user);
    }

    public void updateBuffer() {
        ContentResolver resolver = mContext.getContentResolver();
        Cursor cursor = resolver.query(sUserUri, null, "is_login = ?", new String[] {"1"}, null);
        if (cursor == null || cursor.moveToFirst() == false) {
            return ;
        }
        long loginTime = cursor.getLong(10);
        if (isLoginOverdu(loginTime)) {
            logout();
            mLoginUser = null;
        } else {
            mLoginUser = mapUser(cursor);
        }
    }

    public void logout() {
        ContentValues values = new ContentValues();
        values.put("is_login", 0);
        ContentResolver resolver = mContext.getContentResolver();
        resolver.update(sUserUri, values, null, null);
        mLoginUser = null;
        latitude = 0.0D;
        longitude = 0.0D;
    }

    /**
     * 插入一条新的用户记录
     * @param user
     */
    public synchronized void insertUser(User user) {
        if (user == null) {
            return ;
        }
        ContentValues userValues = setupUserContentValue(user, true);
        ContentResolver resolver = mContext.getContentResolver();
        resolver.insert(sUserUri, userValues);
    }

    public synchronized void updateUser(User user, boolean updateLoginTime) {
        if (user == null) {
            return ;
        }
        ContentValues userValues = setupUserContentValue(user, updateLoginTime);
        ContentResolver resolver = mContext.getContentResolver();
        resolver.update(sUserUri, userValues, "user_id = ?", new String[] {user.getUserId()});
    }

    public void saveLocation(double latitude, double longitude) {
        this.latitude = latitude;
        this.longitude = longitude;
    }

    public boolean hasLocationInfo() {
        return !(latitude == 0.0D && longitude == 0.0D);
    }

    public double getLongitude() {
        return longitude;
    }

    public double getLatitude() {
        return latitude;
    }
}
